package com.bdqn.service.platformlist.push;

import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import com.alibaba.fastjson.JSONObject;
import com.bdqn.common.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JiGuangPushUtil {

    private static final Logger log = LoggerFactory.getLogger(JiGuangPushUtil.class);
    //两个参数分别填写你申请的masterSecret和appKey
    private static JPushClient jPushClient=new JPushClient("b686d49dcbf58b1bfda71329","2256ff3a9699df46386eef47");

    /**
     * 全平台指定用户极光透传
     *
     * @param clientId 标题
     * @param body 消息内容
     * @param to app跳转表识
     * @return
     */
    public PushPayload sendAllPush(String clientId, Map<String, Object> body, String to) {
        String param= JSONObject.toJSONString(body);
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.registrationId(clientId))
                .setMessage(Message.newBuilder()
                        .setMsgContent(param)
                        .setTitle(body.get("platform").toString())
                        .addExtra("to", to)
                        .build())
                .build();
        return payload;
    }

    /**
     * 指定用户极光透传
     *
     * @param clientId
     * @param body
     * @return
     */
    public Boolean transmit(String clientId,Map<String, Object> body) {
        try {
            if(null == clientId || "".equals(clientId)){
                return false;
            }
            body.put("date", DateUtil.getLongDate(new Date()));
            PushPayload payload = sendAllPush(clientId,body,"");
            PushResult result = jPushClient.sendPush(payload);
            log.info(JSONObject.toJSONString(result));
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     *
     * @param name  平台拼音
     * @param objects  1 message 状态信息  2 code  状态码 参考--> VerifyCodeUtil
     * @return
     */
    public Map<String,Object> productionMessage(String name, Object... objects){
        Map<String,Object> map=new HashMap<>();
        map.put("platform",name);
        if(objects[0]!=null && !"".equals(objects[0])){
            map.put("message",objects[0]);
        }
        if(objects.length>=2 && objects[1]!=null){
            map.put("code",objects[1]);
        }
        if(objects.length>=3 && objects[2]!=null){
            map.put("space",objects[2]);
        }
        return map;
    }

}
